"""卖家对话消息业务逻辑"""

import json
from typing import Dict, Optional
from loguru import logger

from sqlalchemy.ext.asyncio import AsyncSession

from module_admin.dao.seller_message_dao import SellerMessageDao
from module_admin.entity.do.seller_message_do import SellerMessage
from module_admin.entity.vo.seller_message_vo import (
    SellerMessageModel,
    SellerMessageQueryModel,
)


class SellerMessageService:
    """卖家消息 Service"""

    @classmethod
    async def get_message_list(
        cls,
        db: AsyncSession,
        query_params: SellerMessageQueryModel,
        page_num: int = 1,
        page_size: int = 10,
        current_user_id: int = None,
        is_admin: bool = True
    ) -> Dict:
        """获取消息列表（支持权限过滤）
        
        Args:
            db: 数据库会话
            query_params: 查询参数
            page_num: 页码
            page_size: 每页数量
            current_user_id: 当前用户ID
            is_admin: 是否是管理员（role_id=1的超级管理员）
        """
        messages, total = await SellerMessageDao.get_message_list(
            db=db,
            query_params=query_params,
            page_num=page_num,
            page_size=page_size,
            current_user_id=current_user_id,
            is_admin=is_admin
        )

        # ✅ 构建增强的消息模型（包含解析后的message_extra）
        import html
        import json
        enhanced_messages = []
        for msg in messages:
            msg_dict = SellerMessageModel.model_validate(msg).model_dump()
            
            # ✅ 解析message_extra（JSON格式）
            if msg.message_extra:
                try:
                    extra_data = json.loads(msg.message_extra) if isinstance(msg.message_extra, str) else msg.message_extra
                    
                    # ✅ 根据消息类型提取特定字段
                    if msg.message_type == 'image' and extra_data:
                        msg_dict['image_url'] = extra_data.get('image_url')
                        msg_dict['image_width'] = extra_data.get('image_width')
                        msg_dict['image_height'] = extra_data.get('image_height')
                    
                    elif msg.message_type == 'voice' and extra_data:
                        msg_dict['voice_url'] = extra_data.get('voice_url')
                        msg_dict['voice_duration'] = extra_data.get('voice_duration')
                    
                    elif msg.message_type == 'video' and extra_data:
                        msg_dict['video_url'] = extra_data.get('video_url')
                        msg_dict['video_cover'] = extra_data.get('video_cover')
                        msg_dict['video_duration'] = extra_data.get('video_duration')
                        msg_dict['video_width'] = extra_data.get('video_width')
                        msg_dict['video_height'] = extra_data.get('video_height')
                    
                    # ✅ 系统消息：提取system_data并解码HTML
                    elif msg.message_type == 'system' or msg.custom_content_type == 6:
                        system_data = extra_data.get('system_data')
                        if system_data:
                            # ✅ 解码HTML实体（只对系统消息）
                            title = system_data.get('title', '')
                            content = system_data.get('content', '')
                            if title:
                                system_data['title'] = html.unescape(title)
                            if content:
                                system_data['content'] = html.unescape(content)
                            
                            msg_dict['system_data'] = system_data
                            
                            # ✅ 如果message_content是HTML，也解码
                            if msg.message_content and msg.message_content.strip():
                                msg_dict['message_content'] = html.unescape(msg.message_content)
                            else:
                                # ✅ 如果message_content为空或NULL，使用title作为显示内容
                                msg_dict['message_content'] = system_data.get('title', '[系统消息]')
                            
                            logger.debug(f"✅ 提取系统消息: message_id={msg.message_id}, title={system_data.get('title', '')[:50]}")
                    
                    # ✅ 保留原始extra数据
                    msg_dict['extra_data'] = extra_data
                except json.JSONDecodeError:
                    logger.warning(f"消息extra解析失败: message_id={msg.message_id}, extra={msg.message_extra}")
            
            enhanced_messages.append(msg_dict)

        return {
            "rows": enhanced_messages,
            "total": total
        }

    @classmethod
    async def create_message(
        cls,
        db: AsyncSession,
        data: dict,
        create_by: int = 0,
        dept_id: int = 0
    ) -> SellerMessageModel:
        message = SellerMessage(
            conversation_id=data.get('conversation_id'),
            chat_id=data.get('chat_id'),  # ✅ 添加chat_id字段
            message_id=data.get('message_id'),
            temp_id=data.get('temp_id'),  # ✅ 消息状态机：前端临时ID
            mid=data.get('mid'),  # ✅ 消息状态机：消息mid
            client_id=data.get('client_id'),
            # client_name 和 account_user_id 字段不存在于数据库模型，已移除
            seller_id=data.get('seller_id'),
            seller_name=data.get('seller_name'),
            seller_avatar=data.get('seller_avatar'),
            item_id=data.get('item_id'),
            item_title=data.get('item_title'),
            message_type=data.get('message_type') or 'text',
            direction=data.get('direction') or 'recv',
            message_content=data.get('message_content'),
            message_extra=data.get('message_extra'),
            content_type=data.get('content_type'),
            custom_content_type=data.get('custom_content_type'),
            read_status=data.get('read_status'),
            create_at=data.get('create_at'),
            message_time=cls._ensure_datetime(data.get('message_time')),
            message_status=data.get('message_status', 2),  # ✅ 消息状态机：默认SENT
            create_by=create_by,
            dept_id=dept_id
        )

        created = await SellerMessageDao.create_message(db, message)
        return SellerMessageModel.model_validate(created)

    @classmethod
    async def delete_message(cls, db: AsyncSession, message_id: int):
        await SellerMessageDao.delete_message(db, message_id)

    @staticmethod
    def _ensure_datetime(value):
        from datetime import datetime

        if value is None:
            return None
        if isinstance(value, datetime):
            return value
        try:
            return datetime.fromisoformat(str(value))
        except ValueError:
            return datetime.now()
